#include "stdafx.h"
#include "service\storage\file\TeamFileService.h"
#include "service\storage\file\PlayerFileService.h"
#include "model\BaseModel.h"
#include "model\Team.h"
#include "lib\SimpleCSV.h"
#include "Application.h"
#include <string>


TeamFileService::TeamFileService() {

}


TeamFileService::TeamFileService(std::fstream& file) : BaseFileService(file) {

}


TeamFileService::~TeamFileService() {

}


BaseFileService& TeamFileService::Load(BaseModel* model) {
  Team *team = reinterpret_cast<Team*>(model);
  file() >> *team;
  int numplayers;
  file() >> numplayers;
  file().ignore();
  int id;
  for (int i = 0; i < numplayers; ++i) {
    std::string tmp;
    std::getline(file(), tmp);
    SimpleCSV csv(tmp);
    if (!csv[1].empty()) {
      id = Application::CreatePlayer(csv[0], csv[1]).id();
    } else {
      id = atoi(csv[0].c_str());
    }
    team->AddPlayer(id);
  }
  return *this; 
}


BaseFileService& TeamFileService::Save(const BaseModel& model) {
  Team team = reinterpret_cast<const Team&>(model);
  file() << team << '\n';
  file() << team.NumPlayers() << '\n';
  TCollection<int>::CollectionPair playeriters = team.GetPlayers();
  for (; playeriters.first != playeriters.second; ++playeriters.first) {
    file() << *playeriters.first << '\n';
  }
  return *this;
} 